/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Controlador;

import Dao.ClienteDAO;
import Dto.ClienteDTO;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author -ADMIN-
 */
public class Controlador extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        
        if(request.getParameter("accion") != null){
            
            String accion = request.getParameter("accion");
            HttpSession sesion = request.getSession(false);
            
            if(accion.equals("ModificarDatos")){
                 this.actualizarDatosUsuario(request, response);
            }else if(accion.equals("iniciarSesion")){
                 this.iniciarSesion(request, response);
            }else if(accion.equals("registroCliente")){
                 this.registroUsuarios(request, response);
            }else if(accion.equals("cambioClave")){
                this.cambioClaveUsuario(request, response);
            }else if (accion.equals("reestablecerClave")) {
                this.reestablecerClave(request, response);
            }
        }else{
            response.sendRedirect("error404.jsp?msg=no puede ingresar");
        }
        
        
    }
    
     private void iniciarSesion(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         
        HttpSession session = request.getSession();
        String email = request.getParameter("txtUser");
        String pass = request.getParameter("txtPass");
            
        try{
         ClienteDTO cdto = ClienteDAO.validarInicioSesion(email, pass);
            if(cdto != null){
                // validar para saber que rol esta ingresando.
                String rol = ClienteDAO.consultarRolUsuario(cdto.getId());                
                if(null != rol)switch (rol) {
                 case "admin":
                     session.setAttribute("admin", cdto);
                     session.setAttribute("user", cdto);
                     response.sendRedirect("Pages/inicioAdministrador.jsp");
                     break;
                 case "cliente":
                     session.setAttribute("user", cdto);
                     response.sendRedirect("Pages/inicioCliente.jsp");
                     break;
             }
            }else{
                response.sendRedirect("Pages/index.jsp?msg= Usuario no valido ");
            }
        }catch(NullPointerException npe){
            response.sendRedirect("Pages/error404.jsp?msg=no existe conexion a DB");
        }
        
     }   
     
      private void registroUsuarios(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
          
          int id  = Integer.parseInt(request.getParameter("txtId"));
          String nombre = request.getParameter("txtName");
          String ape1 = request.getParameter("txtApellido1");
          String ape2 = request.getParameter("txtApellido2");
          String fecha = request.getParameter("txtFechaNac");          
          String direccion = request.getParameter("txtDireccion");
          // int cel = Integer.parseInt(request.getParameter("txtCelular"));
          Long cel = Long.parseLong(request.getParameter("txtCelular"));
          String correo = request.getParameter("txtCorreo");
          String clave = request.getParameter("txtClave");
          
          int rpta = ClienteDAO.registroCliente(new ClienteDTO(id, nombre, ape1, ape2, fecha, direccion, cel, correo, clave));
          
          if(rpta == 1){
              response.sendRedirect("Pages/registro.jsp?msg=Registro Exitoso");
          }else if(rpta == 2){
              response.sendRedirect("Pages/registro.jsp?msg=Error identificacion ya registrada");
          }else if(rpta == 3){
              response.sendRedirect("Pages/registro.jsp?msg=Correo ya esta siendo usado");
          }
          
      }
     
     private void actualizarDatosUsuario(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         
        HttpSession sesion = request.getSession(false);
        ClienteDTO pdto = (ClienteDTO) sesion.getAttribute("user");
        
          int id  = Integer.parseInt(request.getParameter("txtId"));
          String nombre = request.getParameter("txtName");
          String ape1 = request.getParameter("txtApellido1");
          String ape2 = request.getParameter("txtApellido2");
          String fecha = request.getParameter("txtFechaNac");          
          String direccion = request.getParameter("txtDireccion");
          Long cel = Long.parseLong(request.getParameter("txtCelular"));
          String correo = request.getParameter("txtCorreo");
          
          boolean rpta = ClienteDAO.updateDatosCliente(new ClienteDTO(id, nombre, ape1, ape2, fecha, direccion, cel, correo));
          if(rpta == true){
              
              pdto.setNombre(nombre);
              pdto.setApellido1(ape1);
              pdto.setApellido2(ape2);
              pdto.setNacido(fecha);
              pdto.setDireccion(direccion);
              pdto.setCel(cel);
              pdto.setCorreo(correo);
              
              response.sendRedirect("Pages/inicioCliente.jsp?msg=Datos actualizados");
          }
          else{
              response.sendRedirect("Pages/ActualizarPerfil.jsp?msg=No se puede actualizar");
          }
     }    
     
      private void cambioClaveUsuario(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
          
          HttpSession sesion = request.getSession(false);
          ClienteDTO pdto = (ClienteDTO) sesion.getAttribute("user");
          int ide = pdto.getId();
          String claveActual = request.getParameter("txtClaveActual");
          String claveNueva = request.getParameter("txtClave");
          
          int result = ClienteDAO.cambioClave(ide, claveActual, claveNueva);
          
          if(result == 1)
            response.sendRedirect("Pages/ActualizarPerfil.jsp?msg=Clave Cambiada Exitosamente");  
          else
              response.sendRedirect("Pages/CambioClave.jsp?msg= Clave actual no se digito correctamente");
          
          
      }

      private void reestablecerClave(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
          
          String email = request.getParameter("txtCorreo");
          String clave = request.getParameter("txtClave");
          
          int valor = ClienteDAO.reestablecerClave(email, clave);
          if (valor == 1) {
              response.sendRedirect("Pages/reestablecerClave.jsp?msg=Cambio de clave exitoso");
          }else{
              response.sendRedirect("Pages/reestablecerClave.jsp?msg=Correo ingresado no se encuentra registrado");
          }
          
      }
     
   
     
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
